<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" th:replace="~{layout3.html :: layout(~{::title}, ~{::section}, ~{::scriptAfterBody})}">
<head>
  <title>仪表盘</title>
</head>
<body>

<section>
<div class="row">
  <div class="col">
    <div class="card">
      <div class="card-body">
        <div class="row">
          <div class="col">
            <div class="card">
              <div class="card-body">
                <!-- Button trigger modal -->

                <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
                  <div class="btn-group me-2" role="group" aria-label="First group">
                    <button type="button" class="btn btn-outline-primary"  data-bs-toggle="modal" data-bs-target="#staticBackdrop">创建租户</button>
                    <button type="button" class="btn btn-outline-primary">设置激活码</button>
                    <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#modalRenew" >续期</button>

                  </div>
                </div>
                <!-- Modal -->
                <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                  <div class="modal-dialog">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title" id="staticBackdropLabel">创建租户</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                      </div>
                      <div class="modal-body modal-dialog-centered">
                        <div class="container">
                          <div class="row">
                            <div class="col-md-8 col-lg-6 col-xl-4">
                              <div class="card register-box-container">
                                <div class="card-body">
<!--                                  <div class="authent-logo"><img src="../static/images/logo-new.png" alt=""></div>-->
                                  <form id="createTenantForm" class="needs-validation" novalidate>
                                    <div class="mb-3">
                                      <div class="form-floating">
                                        <input type="text" class="form-control"  name="name" placeholder="名称" required>
                                        <label for="floatingInput">名称</label>
                                      </div>
                                    </div>
                                    <div class="mb-3">
                                      <div class="form-floating">
                                        <input type="email" class="form-control"  name="mobile" placeholder="手机号" required>
                                        <label for="floatingInput">手机号</label>
                                      </div>
                                    </div>
                                    <div class="mb-3">
                                      <div class="form-floating">
                                        <input type="password" class="form-control"  name="password" placeholder="Password" required>
                                        <label >密码</label>
                                      </div>
                                    </div>
                                    <div class="mb-3">
                                      <div class="form-floating">
                                        <input type="password" class="form-control"  name="confirmPassword" placeholder="Confirm Password" required>
                                        <label>Confirm Password</label>
                                      </div>
                                    </div>
                                      <div class="mb-3 col-sm-10">
                                        <div class="form-check">
                                          <input class="form-check-input" type="radio" name="storeType" id="gridRadios1" value="1"   required>
                                          <label class="form-check-label" for="gridRadios1">云店 </label>
                                        </div>
                                        <div class="form-check">
                                          <input class="form-check-input" type="radio" name="storeType" id="gridRadios2" value="2">
                                          <label class="form-check-label" for="gridRadios2">门店 </label>
                                        </div>
                                      </div>
                                    <div class="mb-3">
                                      <div class="form-floating">
                                      <input  type="text"  id="datetime-picker1" name="expireTime" class="form-control datetime-picker" placeholder="请选择日期和时间" required >
                                        <label for="datetime-picker1" class="form-label">有效期</label>
                                      </div>
                                    </div>

                                  </form>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" id="createTenantButton" class="btn btn-primary">提交</button>
                      </div>
                    </div>
                  </div>
                </div>





              </div>
            </div>
          </div>
        </div>

        <div id="result" class="mt-2"></div>
        <table id="tenantTable" class="display" style="width:100%">
          <thead>
          <tr>
            <th>名称</th>
            <th>手机号</th>
            <th>有效期</th>
            <th>版本</th>
          </tr>
          </thead>
<!--          <tbody id="tenantTableBody">-->

<!--          </tbody>-->
          <tfoot>
          <tr>
            <th>名称</th>
            <th>手机号</th>
            <th>有效期</th>
            <th>版本</th>

          </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>
</div>


  <!-- Modal -->
  <div class="modal fade" id="modalRenew" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="modalRenewLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="modalRenewLabel">续期</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body modal-dialog-centered">
          <div class="container">
            <div class="row">
              <div class="col-md-8 col-lg-6 col-xl-4">
                <div class="card register-box-container">
                  <div class="card-body">
                    <form>
                      <div class="mb-3">
                        <div class="form-floating">
                          <input type="text" class="form-control" id="floatingInput" placeholder="名称">
                          <label for="floatingInput">名称</label>
                        </div>
                      </div>
                      <div class="mb-3">
                        <div class="form-floating">
                          <input type="email" class="form-control" id="floatingInput1" placeholder="手机号">
                          <label for="floatingInput">手机号</label>
                        </div>
                      </div>
                      <div class="mb-3">
                        <div class="form-floating">
                          <input type="text"class="form-control datetime-picker" placeholder="请选择日期和时间">
                          <label   class="form-label">有效期</label>
                        </div>
                      </div>
                      <div class="d-grid">
                        <button type="submit" class="btn btn-primary m-b-xs">Register</button>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Understood</button>
        </div>
      </div>
    </div>
  </div>

</section>
<div th:insert="~{footer :: copy}"></div>

</body>

<scriptAfterBody>
<script language="JavaScript" id="scriptAfterBody">

  $('.datetime-picker').each(function() {
  $(this).flatpickr({
    enableTime: true,
    noCalendar: false,
    dateFormat: "Y-m-d H:i:S",
    locale: "zh",
    time_24hr: true,
    enableSeconds: true,
    defaultDate: function() {
      const now = new Date();
      return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
    },
    // 方案1：只允许特定小时（12和23），再限制分钟和秒
    hourIncrement: 12,
    minuteIncrement: 0, // 分钟步长设为59（配合后续过滤）
    secondIncrement: 0,
    // 方案2：通过过滤函数保留允许的时间
    onValueUpdate: function(selectedDates, dateStr, instance) {
      const selected = selectedDates[0];
      if (!selected) return;

      const hours = selected.getHours();
      const minutes = selected.getMinutes();
      const seconds = selected.getSeconds();
      // 只保留 12:00:00 和 23:59:59
      const validTimes = [
        {h:12, m:0, s:0},
        {h:23, m:59, s:59}
      ];

      // 检查当前选中时间是否有效
      const isValid = validTimes.some(t =>
        t.h === hours && t.m === minutes && t.s === seconds
      );

<!--      if (!isValid) {-->
<!--        // 无效时自动切换到默认时间（23:59:59）-->
<!--        const now = new Date();-->
<!--        instance.setDate(new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59));-->
<!--      }-->
    },
    // 确保选择框能正常打开
    onOpen: function() {
      console.log('选择框已打开'); // 用于验证是否触发
    }
  });
});

    // 当前选中的行数据
      let selectedRow = null;

    function bindSelectRow() {
      document.querySelectorAll(".btn-group .btn").forEach(btn => {
        btn.addEventListener("click", () => {
          const action = btn.getAttribute("data-action"); // 获取按钮动作标识
        const resultEl = document.getElementById("result");
        if (!selectedRow) {
          resultEl.innerHTML = `<span class="text-danger">请先选中一行数据</span>`;
          return;
        }

        const data = selectedRow.data;
        alert(JSON.stringify(data));
        });
      });
      }




   $(document).ready(function() {
    var tenantTable = $('#tenantTable').DataTable({
      serverSide: true,
      processing: true,
      stateSave: false,
      select: 'single',
      ajax: {
        url: 'http://localhost:8080/supper/tenant/search2',
        type: 'POST',
        contentType: 'application/json',
        // 前端传递给后端的参数（pageNO从1开始，符合常见后端分页逻辑）
        data: function(d) {
          return JSON.stringify({
            draw: d.draw,
            pageNO: Math.floor(d.start / d.length) + 1, // 计算当前页码（1-based）
            pageSize: d.length, // 每页条数（对应后端pageSize）
            name: d.search.value // 搜索关键词
          });
        },
        // 关键：转换后端返回的数据格式，适配DataTables要求
  <!--      dataSrc: function(response) {-->
  <!--        return {-->
  <!--          draw: response.draw,-->
  <!--          recordsTotal: response.recordsTotal, // 总数据量（必须正确）-->
  <!--          recordsFiltered: response.recordsFiltered, // 过滤后的数据量（同总数据量则表示无过滤）-->
  <!--          data: response.data // 当前页数据-->
  <!--        };-->
  <!--      }-->
      },
      columns: [
        { data: 'name' },
        { data: 'mobile' },
        {
          data: 'storeType',
          render: function(data) {
            return data === 1 ? '云店' : '门店';
          }
        },
        {
          data: 'expireAt',
          render: function(data) {
            // 格式化时间（去除T和毫秒部分）
            return data ? data.replace('T', ' ').split('.')[0] : '无过期时间';
          }
        }
      ],
      pageLength: 10,
      lengthMenu: [5, 10, 20, 50],
      pagingType: 'full_numbers',
      language: {
        info: '显示第 _PAGE_ 页，共 _PAGES_ 页',
        infoEmpty: '无记录',
        infoFiltered: '(从 _MAX_ 条记录中筛选)',
        lengthMenu: '每页显示 _MENU_ 条',
        zeroRecords: '未找到匹配记录',
        processing: '加载中...' // 增加加载提示
      }
    });



     $('#tenantTable tbody').on('click', 'tr', function() {
      // 1. 取消所有行的选中状态
      tenantTable.rows().nodes().to$().removeClass('selected');
      // 2. 选中当前行（添加样式类）
      $(this).addClass('selected');

      // 3. （可选）获取选中行的数据，用于后续业务
      const selectedData = tenantTable.row(this).data();
      console.log('当前选中行数据：', selectedData);
      // 例如：记录选中ID
      // const selectedId = selectedData.id;
    });


      const createTenantForm = document.getElementById('createTenantForm');
      createTenantForm.addEventListener('submit', function(e) {
           e.preventDefault();
             const $form = $(this);
         const isPass = validateExpireTime();

           if (!$form[0].checkValidity()) {
            // 显示原生错误提示
            $form[0].reportValidity();
            $form.addClass('was-validated'); // 标记错误样式
            return; // 不执行 AJAX
          }
          if (!isPass) {
          return;
          }
          const jsonData = formToJson(this);
           fetch('/supper/tenant/create', {
           method: 'POST', // 明确指定 POST 方法
            headers: {
              'Content-Type': 'application/json' // 告诉服务器发送的是 JSON
            },
            body: JSON.stringify(jsonData)
          })
          .then(response => response.json())
          .then(result => {
            console.log('提交成功，服务器返回：', result);
          })
          .catch(error => {
            console.error('提交失败：', error);
          });
      });

    document.getElementById('createTenantButton').addEventListener('click', function() {
    createTenantForm.dispatchEvent(new Event('submit'));
    });

  });


  // 自动将 form 元素转为 JSON 对象
function formToJson(form) {
  const formData = new FormData(form); // 先通过 FormData 收集所有表单数据
  const jsonData = {};

  // 遍历 FormData 中的键值对，组装成 JSON 对象
  formData.forEach((value, key) => {
    // 处理复选框（多个同 name 的复选框，值应为数组）
    if (jsonData[key] !== undefined) {
      // 如果已有该 key，转为数组
      if (!Array.isArray(jsonData[key])) {
        jsonData[key] = [jsonData[key]];
      }
      jsonData[key].push(value);
    } else {
      jsonData[key] = value;
    }
  });

  return jsonData;
}
    const errorStyle = `
      border-color: #dc3545 !important;
      box-shadow: 0 0 0 0.25rem rgba(220, 53, 69, 0.25) !important;
    `;
    const defaultStyle = ''; // 恢复默认样式
 function validateExpireTime() {
  const $input = $('#datetime-picker1');
  const timeValue = $input.val().trim();

  if (timeValue === "") {
    // 1. 输入框变红（直接加内联错误样式）
    $input.attr('style', errorStyle);
    // 2. 设置原生错误信息（触发浏览器提示）
    $input[0].setCustomValidity('请选择有效期');
    // 3. 弹出浏览器原生提示（即使 readonly 也会触发）
    $input[0].reportValidity();
    return false; // 校验失败
  } else {
    // 校验通过：恢复默认样式+清空错误
    $input.attr('style', defaultStyle);
    $input[0].setCustomValidity('');
    return true; // 校验通过
  }
}
</script>
</scriptAfterBody>
</html>